package com.zui.security;

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.sun.istack.internal.NotNull;
import com.zui.entity.BaseAutoIdEntity;
/**
 * 角色表
 * @author SHIJUN
 * @version 1.02008-8-14
 */
@Entity
@Table(name = "security_role")
public class Role  extends BaseAutoIdEntity {
	private static final long serialVersionUID = 1L;
	
	public Role(){}
	public Role(Long id){
		this.id = id;
	}
	
	private String roleName;
	private String roleType;
	/**
	 * 角色可以访问的所有资源集合
	 */
	private Set<Resource> resources = new LinkedHashSet<Resource>();
	/**
	 * 拥有此角色的所有用户集合
	 */
	private Set<User> users = new LinkedHashSet<User>();
	
	/*------------------------------
	 * Form specific fields and Business Methods
	 --------------------------------*/	
	/**
	 * 得到当前角色的所有权限名
	 * @return 权限名组成的字符串
	 */
	@Transient
	public String getAuthorities(){
		StringBuffer sb = new StringBuffer();
		if(resources == null || resources.size() == 0)
			return "";
		for(Iterator<Resource> it = resources.iterator(); it.hasNext();){
			sb.append(it.next().getId());
			sb.append(",");
		}
		return sb.toString().substring(0,sb.toString().length()-1);
	}

	/*------------------------------
	 * getters and annotations
	 --------------------------------*/	

	@Column(length=20,unique=true) @NotNull
	public String getRoleName() {return roleName;}
	
	public String getRoleType() {return roleType;}
	
	@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE},
			fetch = FetchType.LAZY)
	@JoinTable(name="security_role_resource",
			joinColumns = {@JoinColumn(name = "roleId",referencedColumnName = "id")},
			inverseJoinColumns = {@JoinColumn(name="resourceId",referencedColumnName = "id")})
	@OrderBy(value="orderIndex")
	public Set<Resource> getResources() {return resources;}
	
	@ManyToMany(mappedBy="roles", fetch = FetchType.LAZY)
	@OrderBy("userName")
	public Set<User> getUsers() {
		return users;
	}
	
	/*------------------------------
	 * setters
	 --------------------------------*/	
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	public void setRoleType(String roleType) {
		this.roleType = roleType;
	}
	public void setResources(Set<Resource> resources) {
		this.resources = resources;
	}
	public void setUsers(Set<User> users) {
		this.users = users;
	}
}
